// store/modules/user.js
import config from '../../config'
import storage from '../../utils/stotage'
import constant from '../../utils/constant'
import { isHttp, isEmpty } from "../../utils/validate"
import { login, logout, getInfo } from '../../api/login'
import { getToken, setToken, removeToken } from '../../utils/auth'
import store from '../index.js'

// 默认头像路径
const defAva = '../../static/images/profile.jpg'

const baseUrl = config.baseUrl

const user = {
  // 登录
  Login(userInfo) {
    const username = userInfo.username.trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    return new Promise((resolve, reject) => {
      login(username, password, code, uuid).then(res => {
        store.setToken(res.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  GetInfo() {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const user = res.user
        let avatar = user.avatar || ""
        if (!isHttp(avatar)) {
          avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar
        }
        const userid = (isEmpty(user) || isEmpty(user.userId)) ? "" : user.userId
        const username = (isEmpty(user) || isEmpty(user.userName)) ? "" : user.userName
        if (res.roles && res.roles.length > 0) {
          store.setRoles(res.roles)
          store.setPermissions(res.permissions)
        } else {
          store.setRoles(['ROLE_DEFAULT'])
        }
        store.setId(userid)
        store.setName(username)
        store.setAvatar(avatar)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出系统
  LogOut() {
    return new Promise((resolve, reject) => {
      logout(store.getToken()).then(() => {
        store.clear()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default user